﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using VAdvantage.Utility;
using VAdvantage.Grids;
using VAdvantage.Model;
using VAdvantage.Classes;
using VAdvantage.Logging;
using VAdvantage.Controls;
using System.Collections;
using System.Data;
using VAdvantage.DataBase;
using System.Threading;
using VAdvantage.Process;

namespace VAdvantage.Framework
{
    public partial class VPayment : ChildWindow
    {
        #region Private Variables
        Ctx ctx = Envs.GetCtx();
        //	Window					
        private int _WindowNo = 0;
        //	Tab						
        private GridTab _mTab;
        //	Data from Order/Invoice
        private String _DocStatus = null;
        // Start Payment Rule       
        private String _PaymentRule = "";
        // Start Payment Term       
        private int _C_PaymentTerm_ID = 0;
        // Start Acct Date          
        private DateTime? _DateAcct = null;
        // Start Payment            
        private int _C_Payment_ID = 0;
        private MPayment _mPayment = null;
        private MPayment _mPaymentOriginal = null;
        // Start CashBook Line      
        private int _C_CashLine_ID = 0;
        private MCashLine _cashLine = null;
        // Start CreditCard         
        private String _CCType = "";
        // Start Bank Account		
        private int _C_BankAccount_ID = 0;
        // Start CashBook           
        private int _C_CashBook_ID = 0;
        // Is SOTrx					
        private bool _isSOTrx = true;
        // Invoice Currency              
        private int _C_Currency_ID = 0;
        private int _AD_Client_ID = 0;
        private int _AD_Org_ID = 0;
        private int _C_BPartner_ID = 0;
        private Decimal _Amount = Envs.ZERO;	//	Payment Amount
        private bool _needSave = false;
        private bool _initOK = false;
        private bool _OKpressed = false;
        // Only allow changing Rule        
        private bool _onlyRule = false;
        //private DecimalFormat 		_Format = DisplayType.getNumberFormat(DisplayType.Amount);
        private Format _Format = DisplayType.GetNumberFormat(DisplayType.Amount);

        //private static Hashtable<int, KeyNamePair> _Currencies = null;	//	EMU Currencies
        private static IDictionary<int, KeyNamePair> _Currencies = null;	//	EMU Currencies
        //Logger	
        private static VLogger log = VLogger.GetVLogger(typeof(VPayment).FullName);
        #endregion

        #region Form Design

        //change panel to Grid at run time in order to implementcash rule on window
        private Grid bPanel = new Grid();
        private Grid kPanel = new Grid();
        private Grid tPanel = new Grid();
        private Grid sPanel = new Grid();
        private Grid pPanel = new Grid();

        private VLabel lblKStatus = new VLabel();
        private VLabel lblTStatus = new VLabel();
        private VLabel lblSStatus = new VLabel();
        private VLabel lblBAmountLabel = new VLabel();
        private VLabel lblBAmountField = new VLabel();
        private VLabel lblSAmountLabel = new VLabel();
        private VLabel lblSAmountField = new VLabel();
        private VLabel lblPaymentLabel = new VLabel();
        private VLabel lblKTypeLabel = new VLabel();
        private VLabel lblKNumnerLabel = new VLabel();
        private VLabel lblKExpLabel = new VLabel();
        private VLabel lblTAccountLabel = new VLabel();
        private VLabel lblKApprovalLabel = new VLabel();
        private VLabel lblSNumberLabel = new VLabel();
        private VLabel lblSRoutingLabel = new VLabel();
        private VLabel lblSCurrencyLabel = new VLabel();
        private VLabel lblBCurrencyLabel = new VLabel();
        private VLabel lblPTermLabel = new VLabel();
        private VLabel lblBDateLabel = new VLabel();
        private VLabel lblSCheckLabel = new VLabel();
        private VLabel lblSBankAccountLabel = new VLabel();
        private VLabel lblBCashBookLabel = new VLabel();

        private VAdvantage.Controls.VComboBox cmbPayment = new VComboBox();
        private VAdvantage.Controls.VComboBox cmbKType = new VComboBox();
        private VAdvantage.Controls.VComboBox cmbTAccount = new VComboBox();
        private VAdvantage.Controls.VComboBox cmbSCurrency = new VComboBox();
        private VAdvantage.Controls.VComboBox cmbBCurrency = new VComboBox();
        private VAdvantage.Controls.VComboBox cmbPTerm = new VComboBox();
        private VAdvantage.Controls.VComboBox cmbSBankAccount = new VComboBox();
        private VAdvantage.Controls.VComboBox cmbBCashBook = new VComboBox();

        private VButton btnKOnline = new VButton();
        private VButton btnSOnline = new VButton();

        private VTextBox txtKNumber = new VTextBox();
        private VTextBox txtKExp = new VTextBox();
        private VTextBox txtKApproval = new VTextBox();
        private VTextBox txtSNumber = new VTextBox();
        private VTextBox txtSRouting = new VTextBox();//"",true,false,false,70, 
        private VTextBox txtSCheck = new VTextBox();

        //private ConfirmPanel confirmPanel = new ConfirmPanel(true, false, false, false, false, false, true, VPayment.ActiveForm);

        //private VDate bDateField;
        private VDateTimePicker bDateField = new VDateTimePicker();

        private Grid bPanelLayout = new Grid();// TableLayoutPanel();
        private Grid pPanelLayout = new Grid();
        private Grid centerLayout = new Grid();
        private Grid kLayout = new Grid();
        private Grid tPanelLayout = new Grid();
        private Grid sPanelLayout = new Grid();

        #endregion

        /// <summary>
        /// Default Constructor
        /// </summary>
        public VPayment()
        {
            InitializeComponent();
            LayoutRoot.Background =new SolidColorBrush(GlobalVariable.WINDOW_BACK_COLOR);
            bPanel.Visibility = System.Windows.Visibility.Collapsed;
            kPanel.Visibility = System.Windows.Visibility.Collapsed;
            tPanel.Visibility = System.Windows.Visibility.Collapsed;
            sPanel.Visibility = System.Windows.Visibility.Collapsed;
            pPanel.Visibility = System.Windows.Visibility.Collapsed;
        }

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="windowNo">owning window</param>
        /// <param name="mTab">owning tab</param>
        /// <param name="button">button with access information</param>
        public VPayment(int windowNo, GridTab mTab, IButton button)
            : this()
        {
            Dictionary<String, String> values = button.GetValues();
            this.Title = Msg.GetMsg(Envs.GetCtx(), "Payment");
            _WindowNo = windowNo;
            _isSOTrx = Envs.GetContext().IsSOTrx(windowNo);
            _mTab = mTab;

            // set font of this window
            //InitialFormSetting.SetFont(this);
            Init();
            //_initOK = DynInit(values);    //  Null Pointer if order/invoice not saved yet
            ThreadPool.QueueUserWorkItem(delegate
        {
            _initOK = DynInit(values);
            System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => InvokeDynInit(_initOK));
        });
            this.Show();
            SetBusy(true);

        }
       
        private void SetBusy(bool value)
        {
            this.HasCloseButton = !value;
            busyWindow.Visibility = value ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
            txtBusy.Visibility = value ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
            if (value)
            {
                txtBusy.Text = Msg.GetMsg(Utility.Envs.GetCtx(), "Processing");
            }
            else
            {
                txtBusy.Text = "";
            }
        }


        private void InvokeDynInit(bool _initOK)
        {

            this.cmbPayment.SelectionChanged += new SelectionChangedEventHandler(cmbPayment_SelectionChanged);
            this.cmbKType.SelectionChanged += new SelectionChangedEventHandler(cmbKType_SelectionChanged);
            this.cmbTAccount.SelectionChanged += new SelectionChangedEventHandler(cmbTAccount_SelectionChanged);
            this.cmbSCurrency.SelectionChanged += new SelectionChangedEventHandler(cmbSCurrency_SelectionChanged);
            this.cmbBCurrency.SelectionChanged += new SelectionChangedEventHandler(cmbBCurrency_SelectionChanged);
            this.cmbPTerm.SelectionChanged += new SelectionChangedEventHandler(cmbPTerm_SelectionChanged);
            this.cmbSBankAccount.SelectionChanged += new SelectionChangedEventHandler(cmbSBankAccount_SelectionChanged);
            this.cmbBCashBook.SelectionChanged += new SelectionChangedEventHandler(cmbBCashBook_SelectionChanged);
            this.btnKOnline.Click += new RoutedEventHandler(btnKOnline_Click);
            this.btnSOnline.Click += new RoutedEventHandler(btnSOnline_Click);

            if (!_initOK)
            {
                this.DialogResult = false;
            }
            else
            {
                SetBusy(false);
            }
        }

        /// <summary>
        /// Static Init
        /// </summary>
        private void Init()
        {
            //define table structure
            LayoutTable();
            //cmbPayment.Width = 180;
            //cmbPayment.MaxWidth = 180;

            /**************CreditCard************************/
            #region CreditCard
            //txtKNumber.Width = 180;
            //txtKExp.Width = 180;
            //txtKApproval.Width = 180;

            lblKTypeLabel.Content = Msg.Translate(Envs.GetContext(), "CreditCardType");
            lblKNumnerLabel.Content = Msg.Translate(Envs.GetContext(), "CreditCardNumber");
            lblKExpLabel.Content = Msg.Translate(Envs.GetContext(), "Expires");
            lblKApprovalLabel.Content = Msg.Translate(Envs.GetContext(), "VoiceAuthCode");
            btnKOnline.Content = Msg.Translate(Envs.GetContext(), "Online");
            lblKStatus.Content = "";

            kPanel.Children.Add(kLayout);
            centerPanel.Children.Add(kPanel);

             kLayout.Children.Add(lblKTypeLabel);
            lblKTypeLabel.Margin = new Thickness(3);
            Grid.SetColumn(lblKTypeLabel, 0);
            Grid.SetRow(lblKTypeLabel, 0);

            kLayout.Children.Add(cmbKType);
            cmbKType.Margin = new Thickness(3);
            Grid.SetColumn(cmbKType, 1);
            Grid.SetRow(cmbKType, 0);

            kLayout.Children.Add(lblKNumnerLabel);
            lblKNumnerLabel.Margin = new Thickness(3);
            Grid.SetColumn(lblKNumnerLabel, 0);
            Grid.SetRow(lblKNumnerLabel, 1);

            kLayout.Children.Add(txtKNumber);
            txtKNumber.Margin = new Thickness(3);
            Grid.SetColumn(txtKNumber, 1);
            Grid.SetRow(txtKNumber, 1);

            kLayout.Children.Add(lblKExpLabel);
            lblKExpLabel.Margin = new Thickness(3);
            Grid.SetColumn(lblKExpLabel, 0);
            Grid.SetRow(lblKExpLabel, 2);

            kLayout.Children.Add(txtKExp);
            txtKExp.Margin = new Thickness(3);
            Grid.SetColumn(txtKExp, 1);
            Grid.SetRow(txtKExp, 2);

            kLayout.Children.Add(lblKApprovalLabel);
            lblKApprovalLabel.Margin = new Thickness(3);
            Grid.SetColumn(lblKApprovalLabel, 0);
            Grid.SetRow(lblKApprovalLabel, 3);

            kLayout.Children.Add(txtKApproval);
            txtKApproval.Margin = new Thickness(3);
            Grid.SetColumn(txtKApproval, 1);
            Grid.SetRow(txtKApproval, 3);

            kLayout.Children.Add(btnKOnline);
            btnKOnline.Margin = new Thickness(3);
            Grid.SetColumn(btnKOnline, 1);
            Grid.SetRow(btnKOnline, 4);


            #endregion
            //**************DircetDebit/Credit************************/
            #region DirectDebit/Credit
            lblTAccountLabel.Content = Msg.Translate(Envs.GetContext(), "C_BP_BankAccount_ID");
            lblTStatus.Content = "";

            tPanel.Children.Add(tPanelLayout);
            centerPanel.Children.Add(tPanel);

            tPanelLayout.Children.Add(lblTAccountLabel);
            lblTAccountLabel.Margin = new Thickness(3);
            Grid.SetColumn(lblTAccountLabel, 0);
            Grid.SetRow(lblTAccountLabel, 0); 

            tPanelLayout.Children.Add(cmbTAccount);
            cmbTAccount.Margin = new Thickness(3);
            Grid.SetColumn(cmbTAccount, 1);
            Grid.SetRow(cmbTAccount, 0);
            //cmbTAccount.Width = 180;


           

            #endregion
            //**************Check************************/
            #region Check
            lblSBankAccountLabel.Content = Msg.Translate(Envs.GetContext(), "C_BankAccount_ID");
            lblSAmountLabel.Content = Msg.Translate(Envs.GetContext(), "Amount");
            lblSAmountField.Content = "";
            lblSRoutingLabel.Content = Msg.Translate(Envs.GetContext(), "RoutingNo");
            lblSNumberLabel.Content = Msg.Translate(Envs.GetContext(), "AccountNo");
            lblSCheckLabel.Content = Msg.Translate(Envs.GetContext(), "CheckNo");
            lblSCurrencyLabel.Content = Msg.Translate(Envs.GetContext(), "C_Currency_ID");
            //txtSNumber.Width = 180;
            lblSStatus.Content = "";
            btnSOnline.Content = Msg.Translate(Envs.GetContext(), "Online");

            sPanel.Children.Add(sPanelLayout);
            centerPanel.Children.Add(sPanel);

            sPanelLayout.Children.Add(lblSBankAccountLabel);
            lblSBankAccountLabel.Margin = new Thickness(3);
            Grid.SetColumn(lblSBankAccountLabel, 0);
            Grid.SetRow(lblSBankAccountLabel, 0);

            sPanelLayout.Children.Add(cmbSBankAccount);
            cmbSBankAccount.Margin = new Thickness(3);
            Grid.SetColumn(cmbSBankAccount, 1);
            Grid.SetRow(cmbSBankAccount, 0);

            sPanelLayout.Children.Add(lblSAmountLabel);
            lblSAmountLabel.Margin = new Thickness(3);
            Grid.SetColumn(lblSAmountLabel, 0);
            Grid.SetRow(lblSAmountLabel, 1);

            sPanelLayout.Children.Add(lblSAmountField);
            lblSAmountField.Margin = new Thickness(3);
            Grid.SetColumn(lblSAmountField, 1);
            Grid.SetRow(lblSAmountField, 1);

            sPanelLayout.Children.Add(lblSRoutingLabel);
            lblSRoutingLabel.Margin = new Thickness(3);
            Grid.SetColumn(lblSRoutingLabel, 0);
            Grid.SetRow(lblSRoutingLabel, 2);

            sPanelLayout.Children.Add(txtSRouting);
            txtSRouting.Margin = new Thickness(3);
            Grid.SetColumn(txtSRouting, 1);
            Grid.SetRow(txtSRouting, 2);

            sPanelLayout.Children.Add(lblSNumberLabel);
            lblSNumberLabel.Margin = new Thickness(3);
            Grid.SetColumn(lblSNumberLabel, 0);
            Grid.SetRow(lblSNumberLabel, 3);

            sPanelLayout.Children.Add(txtSNumber);
            txtSNumber.Margin = new Thickness(3);
            Grid.SetColumn(txtSNumber, 1);
            Grid.SetRow(txtSNumber, 3);

            sPanelLayout.Children.Add(lblSCheckLabel);
            lblSCheckLabel.Margin = new Thickness(3);
            Grid.SetColumn(lblSCheckLabel, 0);
            Grid.SetRow(lblSCheckLabel, 4);

            sPanelLayout.Children.Add(txtSCheck);
            txtSCheck.Margin = new Thickness(3);
            Grid.SetColumn(txtSCheck, 1);
            Grid.SetRow(txtSCheck, 4);

            //not know where it will appear in the form
            sPanelLayout.Children.Add(lblSCurrencyLabel);
            lblSCurrencyLabel.Margin = new Thickness(3);
            Grid.SetColumn(lblSCurrencyLabel, 2);
            Grid.SetRow(lblSCurrencyLabel, 0);

            sPanelLayout.Children.Add(cmbSCurrency);
            cmbSCurrency.Margin = new Thickness(3);
            Grid.SetColumn(cmbSCurrency, 3);
            Grid.SetRow(cmbSCurrency, 0);

            sPanelLayout.Children.Add(btnSOnline);
            btnSOnline.Margin = new Thickness(3);
            Grid.SetColumn(btnSOnline, 1);
            Grid.SetRow(btnSOnline, 5);

            //sPanel.Controls.Add(sPanelLayout);
            //centerPanel.Controls.Add(sPanel);
            #endregion
            //**************On Credit************************/
            #region On Credit
            lblPTermLabel.Content = Msg.Translate(Envs.GetContext(), "C_PaymentTerm_ID");
            lblPTermLabel.HorizontalContentAlignment = HorizontalAlignment.Stretch;

            //cmbPTerm.Width = 180;
            pPanel.Children.Add(pPanelLayout);
            centerPanel.Children.Add(pPanel);

            pPanelLayout.Children.Add(lblPTermLabel);
            lblPTermLabel.Margin = new Thickness(3);
            Grid.SetColumn(lblPTermLabel, 0);
            Grid.SetRow(lblPTermLabel, 0);

            pPanelLayout.Children.Add(cmbPTerm);
            cmbPTerm.Margin = new Thickness(3);
            Grid.SetColumn(cmbPTerm, 1);
            Grid.SetRow(cmbPTerm, 0);

            //pPanel.Controls.Add(pPanelLayout);
            //centerPanel.Controls.Add(pPanel);

         
            #endregion
            //**************Cash************************/
            #region Cash
            lblBCashBookLabel.Content = Msg.Translate(Envs.GetContext(), "C_CashBook_ID");
            lblBCashBookLabel.HorizontalContentAlignment = HorizontalAlignment.Stretch;
            
            lblBCurrencyLabel.Content = Msg.Translate(Envs.GetContext(), "C_Currency_ID");
            lblBCurrencyLabel.HorizontalContentAlignment = HorizontalAlignment.Stretch;
            
            lblBAmountLabel.Content = Msg.Translate(Envs.GetContext(), "Amount");
            lblBAmountLabel.HorizontalContentAlignment = HorizontalAlignment. Stretch;
            
            lblBAmountField.Content = "";
            lblBAmountField.HorizontalContentAlignment = HorizontalAlignment.Stretch;
            
            lblBDateLabel.Content = Msg.Translate(Envs.GetContext(), "DateAcct");
            lblBDateLabel.HorizontalContentAlignment = HorizontalAlignment.Stretch;

            bPanel.Children.Add(bPanelLayout);
            centerPanel.Children.Add(bPanel);

            RowDefinition row1 = new RowDefinition();
            row1.Height = new GridLength(0, GridUnitType.Auto);
            RowDefinition row2 = new RowDefinition();
            row2.Height = new GridLength(0, GridUnitType.Auto);
            RowDefinition row3 = new RowDefinition();
            row3.Height = new GridLength(0, GridUnitType.Auto);
            RowDefinition row4 = new RowDefinition();
            row4.Height = new GridLength(0, GridUnitType.Auto);

            bPanelLayout.RowDefinitions.Add(row1);
            bPanelLayout.RowDefinitions.Add(row2);
            bPanelLayout.RowDefinitions.Add(row3);
            bPanelLayout.RowDefinitions.Add(row4);

            ColumnDefinition col1 = new ColumnDefinition();
            col1.Width = new GridLength(0, GridUnitType.Auto);
            ColumnDefinition col2 = new ColumnDefinition();
            col2.Width = new GridLength(0, GridUnitType.Auto);

            bPanelLayout.ColumnDefinitions.Add(col1);
            bPanelLayout.ColumnDefinitions.Add(col2);


            bPanelLayout.Children.Add(lblBCurrencyLabel);
            lblBCurrencyLabel.Margin = new Thickness(3);
            Grid.SetColumn(lblBCurrencyLabel, 0);
            Grid.SetRow(lblBCurrencyLabel, 0);

            bPanelLayout.Children.Add(cmbBCurrency);
            cmbBCurrency.Margin = new Thickness(3);
            Grid.SetColumn(cmbBCurrency, 1);
            Grid.SetRow(cmbBCurrency, 0);

            bPanelLayout.Children.Add(lblBCashBookLabel);
            lblBCashBookLabel.Margin = new Thickness(3);
            Grid.SetColumn(lblBCashBookLabel, 0);
            Grid.SetRow(lblBCashBookLabel, 1);

            bPanelLayout.Children.Add(cmbBCashBook);
            cmbBCashBook.Margin = new Thickness(3);
            Grid.SetColumn(cmbBCashBook, 1);
            Grid.SetRow(cmbBCashBook, 1);

            bPanelLayout.Children.Add(lblBDateLabel);
            lblBDateLabel.Margin = new Thickness(3);
            Grid.SetColumn(lblBDateLabel, 0);
            Grid.SetRow(lblBDateLabel, 2);

            bPanelLayout.Children.Add(bDateField);
            bDateField.Margin = new Thickness(3);
            Grid.SetColumn(bDateField, 1);
            Grid.SetRow(bDateField, 2);

            bPanelLayout.Children.Add(lblBAmountLabel);
            lblBAmountLabel.Margin = new Thickness(3);
            Grid.SetColumn(lblBAmountLabel, 0);
            Grid.SetRow(lblBAmountLabel, 3);

            bPanelLayout.Children.Add(lblBAmountField);
            lblBAmountField.Margin = new Thickness(3);
            lblBAmountField.HorizontalContentAlignment = HorizontalAlignment.Left;
            Grid.SetColumn(lblBAmountField, 1);
            Grid.SetRow(lblBAmountField, 3);


            //bPanel.Controls.Add(bPanelLayout);
            //centerPanel.Controls.Add(bPanel);
            #endregion
        }

        /// <summary>
        /// Design for compleet records
        /// </summary>
        private void LayoutTable()
        {
            //centerPanel.BackColor = Color.Red;
            //centerPanel.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            //kPanel.AutoSize = true;
            //tPanel.AutoSize = true;
            //pPanel.AutoSize = true;
            //bPanel.AutoSize = true;
            //sPanel.AutoSize = true;

            //this.kLayout.AutoSize = true;
            //this.sPanelLayout.AutoSize = true;
            //this.bPanelLayout.AutoSize = true;
            //this.tPanelLayout.AutoSize = true;
            //this.pPanelLayout.AutoSize = true;

            //kPanel.Dock = System.Windows.Forms.DockStyle.Fill;
            //tPanel.Dock = System.Windows.Forms.DockStyle.Fill;
            //pPanel.Dock = System.Windows.Forms.DockStyle.Fill;
            //bPanel.Dock = System.Windows.Forms.DockStyle.Fill;
            //sPanel.Dock = System.Windows.Forms.DockStyle.Fill;

            //this.kLayout.Dock = System.Windows.Forms.DockStyle.Fill;
            //this.sPanelLayout.Dock = System.Windows.Forms.DockStyle.Fill;
            //this.bPanelLayout.Dock = System.Windows.Forms.DockStyle.Fill;
            //this.tPanelLayout.Dock = System.Windows.Forms.DockStyle.Fill;
            //this.pPanelLayout.Dock = System.Windows.Forms.DockStyle.Fill;

            //************CreditCard layout**********************
            // this.kLayout.RowCount = 5;
            this.kLayout.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });
            this.kLayout.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });
            this.kLayout.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });
            this.kLayout.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });
            this.kLayout.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });
            this.kLayout.Name = "Klayout";

            //this.kLayout.ColumnCount = 3;
            this.kLayout.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(170) });
            this.kLayout.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(270) });
            this.kLayout.ColumnDefinitions.Add(new ColumnDefinition() { Width = GridLength.Auto });
            

            //**************Check************************/
            //this.sPanelLayout.ColumnCount = 3;
            this.sPanelLayout.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(170) });
            this.sPanelLayout.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(270) });
            this.sPanelLayout.ColumnDefinitions.Add(new ColumnDefinition() { Width = GridLength.Auto });

            //this.sPanelLayout.RowCount = 6;
            this.sPanelLayout.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });
            this.sPanelLayout.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });
            this.sPanelLayout.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });
            this.sPanelLayout.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });
            this.sPanelLayout.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });
            this.sPanelLayout.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });
            //**************On Credit************************/
            // this.pPanelLayout.ColumnCount = 2;
            this.pPanelLayout.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(170) });
            this.pPanelLayout.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(270) });

            //this.pPanelLayout.RowCount = 1;
            this.pPanelLayout.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });

            //**************Cash************************/
            //this.bPanelLayout.ColumnCount = 2;
            this.bPanelLayout.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(170) });
            this.bPanelLayout.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(270) });

            // this.bPanelLayout.RowCount = 3;
            this.bPanelLayout.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });
            this.bPanelLayout.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });
            this.bPanelLayout.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });

            //**************DircetDebit/Credit************************/
            // this.tPanelLayout.ColumnCount = 2;
            this.tPanelLayout.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(170) });
            this.tPanelLayout.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(270) });

            // this.tPanelLayout.RowCount = 1;
            this.tPanelLayout.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });
        }

        /// <summary>
        /// Dynamic Init.
        /// B (Cash)		(Currency)
        /// K (CreditCard)  Type, Number, Exp, Approval
        /// L (DirectDebit)	BPartner_Bank
        /// P (PaymentTerm)	PaymentTerm
        /// S (Check)		(Currency) CheckNo, Routing
        /// Currencies are shown, if member of EMU
        /// </summary>
        /// <param name="button">payment type button</param>
        /// <returns>true if init OK</returns>
        private bool DynInit(Dictionary<String, String> values)
        {
            try
            {
                _DocStatus = (String)_mTab.GetValue("DocStatus");
                log.Config(_DocStatus);

                if (_mTab.GetValue("C_BPartner_ID") == null)
                {
                    ShowMessage.Error("0", true, Msg.GetMsg(Envs.GetContext(), "SaveErrorRowNotFound", true));
                    return false;
                }

                //  DocStatus
                _DocStatus = (String)_mTab.GetValue("DocStatus");
                if (_DocStatus == null)
                {
                    _DocStatus = "";
                }
                //	Is the Trx closed?		Reversed / Voided / Cloased
                if (_DocStatus.Equals("RE") || _DocStatus.Equals("VO") || _DocStatus.Equals("CL"))
                {
                    return false;
                }
                //  Document is not complete - allow to change the Payment Rule only
                if (_DocStatus.Equals("CO") || _DocStatus.Equals("WP"))
                {
                    _onlyRule = false;
                }
                else
                {
                    _onlyRule = true;
                }
                //	PO only  Rule
                if (!_onlyRule		//	Only order has Warehouse
                    && !_isSOTrx && _mTab.GetValue("M_Warehouse_ID") != null)
                {
                    _onlyRule = true;
                }
                //  Amount
                _Amount = (Decimal)_mTab.GetValue("GrandTotal");
                if (!_onlyRule && _Amount.CompareTo(Envs.ZERO) == 0)
                {
                    //ADialog.error(m_WindowNo, this, "PaymentZero");
                    ShowMessage.Error("", true, Msg.GetMsg(Envs.GetContext(), "PaymentZero", true));
                    return false;
                }

                //Get Data from Grid
                _AD_Client_ID = Convert.ToInt32(_mTab.GetValue("AD_Client_ID"));//.intValue();
                _AD_Client_ID = Convert.ToInt32(_mTab.GetValue("AD_Client_ID"));
                _AD_Org_ID = Convert.ToInt32(_mTab.GetValue("AD_Org_ID"));//.intValue();
                _C_BPartner_ID = Convert.ToInt32(_mTab.GetValue("C_BPartner_ID"));//.intValue();
                _PaymentRule = (String)_mTab.GetValue("PaymentRule");
                _C_Currency_ID = Convert.ToInt32(_mTab.GetValue("C_Currency_ID"));//.intValue();
                _DateAcct = Convert.ToDateTime(_mTab.GetValue("DateAcct"));

                string strKNumber = "";
                string strKExp = "";
                string strKApproval = "";
                string strKStatus = "";
                bool canChange = false;
                string strSRouting = "";
                string strSNumber = "";
                string strSCheck = "";
                string strSStatus = "";
                string strTStatus = "";
                ValueNamePair vp = null;
                KeyNamePair kp = null;
                List<KeyNamePair> loadPaymentTerms = new List<KeyNamePair>();
                List<KeyNamePair> loadAccounts = new List<KeyNamePair>();
                List<KeyNamePair> loadBankAccounts = new List<KeyNamePair>();
                List<KeyNamePair> loadCashBooks = new List<KeyNamePair>();

                if (_mTab.GetValue("C_PaymentTerm_ID") != null || _mTab.GetValue("C_PaymentTerm_ID") != DBNull.Value)
                {
                    _C_PaymentTerm_ID = Convert.ToInt32(_mTab.GetValue("C_PaymentTerm_ID"));//.intValue();
                }
                //  Existing Payment
                if (_mTab.GetValue("C_Payment_ID") != null && _mTab.GetValue("C_Payment_ID") != DBNull.Value)
                {
                    _C_Payment_ID = Util.GetValueOfInt(_mTab.GetValue("C_Payment_ID"));//.intValue();
                    if (_C_Payment_ID != 0)
                    {
                        _mPayment = new MPayment(Envs.GetContext(), _C_Payment_ID, null);
                        _mPaymentOriginal = new MPayment(Envs.GetContext(), _C_Payment_ID, null);	//	full copy
                        //  CreditCard
                        _CCType = _mPayment.GetCreditCardType();
                        strKNumber = _mPayment.GetCreditCardNumber();
                        strKExp = _mPayment.GetCreditCardExp(null);
                        strKApproval = _mPayment.GetVoiceAuthCode();
                        strKStatus = _mPayment.GetR_PnRef();
                        canChange = !_mPayment.IsApproved() || !(_PaymentRule == MOrder.PAYMENTRULE_CreditCard);
                        //	if approved/paid, don't let it change

                        //  Check
                        _C_BankAccount_ID = _mPayment.GetC_BankAccount_ID();
                        txtSRouting.Text = strSRouting;
                        txtSNumber.Text = strSNumber;
                        txtSCheck.Text = strSCheck;
                        lblSStatus.Content = strSStatus;
                        //  Transfer
                        lblTStatus.Content = strTStatus;
                    }
                }
                if (_mPayment == null)
                {
                    _mPayment = new MPayment(Envs.GetContext(), 0, null);
                    _mPayment.SetAD_Org_ID(_AD_Org_ID);
                    _mPayment.SetIsReceipt(_isSOTrx);
                    _mPayment.SetAmount(_C_Currency_ID, _Amount);
                }

                //  Existing Cahbook entry
                _cashLine = null;
                _C_CashLine_ID = 0;
                if (_mTab.GetValue("C_CashLine_ID") != null && _mTab.GetValue("C_CashLine_ID") != DBNull.Value)
                {
                    _C_CashLine_ID = Convert.ToInt32(_mTab.GetValue("C_CashLine_ID"));//.intValue();
                    if (_C_CashLine_ID == 0)
                    {
                        _cashLine = null;
                    }
                    else
                    {
                        _cashLine = new MCashLine(Envs.GetContext(), _C_CashLine_ID, null);
                        _DateAcct = _cashLine.GetStatementDate();
                    }
                }

                if (_Currencies == null)
                {
                    LoadCurrencies();
                }


                //Load Payment Terms
                String SQL = MRole.GetDefault().AddAccessSQL(
                    "SELECT C_PaymentTerm_ID, Name FROM C_PaymentTerm WHERE IsActive='Y' ORDER BY Name",
                    "C_PaymentTerm", MRole.SQL_NOTQUALIFIED, MRole.SQL_RO);

                IDataReader idr = null;
                DataTable dt = null;
                try
                {

                    idr = DB.ExecuteReader(SQL, null, null);
                    dt = new DataTable();
                    dt.Load(idr);
                    idr.Close();
                    foreach (DataRow dr in dt.Rows)
                    {
                        int key = Util.GetValueOfInt(dr[0]);//.getInt(1);
                        String name = dr[1].ToString();//.getString(2);
                        KeyNamePair pp = new KeyNamePair(key, name);
                        //cmbPTerm.Items.Add(pp);
                        loadPaymentTerms.Add(pp);

                        if (key == _C_PaymentTerm_ID)
                        {
                            kp = pp;
                        }
                    }

                }
                catch (Exception ept)
                {
                    if (idr != null)
                    {
                        idr.Close();
                    }
                    log.Log(Level.SEVERE, SQL, ept);
                }
                finally
                {
                    if (idr != null)
                    {
                        idr.Close();
                    }
                    dt = null;
                }



                //Load Accounts
                SQL = "SELECT a.C_BP_BankAccount_ID, NVL(b.Name, ' ')||a.AccountNo AS Acct "
                    + "FROM C_BP_BankAccount a,C_Bank b "
                    + "WHERE C_BPartner_ID=" + _C_BPartner_ID + " AND a.IsActive='Y'";
                kp = null;
                IDataReader idr1 = null;
                try
                {

                    idr1 = DB.ExecuteReader(SQL, null, null);
                    dt = new DataTable();
                    dt.Load(idr1);
                    idr1.Close();
                    foreach (DataRow dr in dt.Rows)
                    {
                        int key = Util.GetValueOfInt(dr[0]);// dr.getInt(1);
                        String name = dr[1].ToString();//.getString(2);
                        KeyNamePair pp = new KeyNamePair(key, name);
                        // cmbTAccount.Items.Add(pp);
                        loadAccounts.Add(pp);
                        /*			kp = pp;*/
                    }

                }
                catch (Exception eac)
                {
                    if (idr1 != null)
                    {
                        idr1.Close();
                    }
                    log.Log(Level.SEVERE, SQL, eac);
                }
                finally
                {
                    if (idr1 != null)
                    {
                        idr1.Close();
                    }
                    dt = null;
                }

                //Load Credit Cards
                ValueNamePair[] ccs = _mPayment.GetCreditCards();

                //Load Bank Accounts
                SQL = MRole.GetDefault().AddAccessSQL(
                    "SELECT C_BankAccount_ID, Name || ' ' || AccountNo, IsDefault "
                    + "FROM C_BankAccount ba"
                    + " INNER JOIN C_Bank b ON (ba.C_Bank_ID=b.C_Bank_ID) "
                    + "WHERE b.IsActive='Y'",
                    "ba", MRole.SQL_FULLYQUALIFIED, MRole.SQL_RO);
                kp = null;
                IDataReader idr2 = null;
                try
                {

                    idr2 = DB.ExecuteReader(SQL, null, null);
                    dt = new DataTable();
                    dt.Load(idr2);
                    idr2.Close();
                    foreach (DataRow dr in dt.Rows)
                    {
                        int key = Util.GetValueOfInt(dr[0]);// dr.getInt(1);
                        String name = dr[1].ToString();//.getString(2);
                        KeyNamePair pp = new KeyNamePair(key, name);
                        //cmbSBankAccount.Items.Add(pp);
                        loadBankAccounts.Add(pp);
                        if (key == _C_BankAccount_ID)
                        {
                            kp = pp;
                        }
                        if (kp == null && dr[2].ToString().Equals("Y"))    //  Default
                        {
                            kp = pp;
                        }
                    }

                }
                catch (Exception ept)
                {
                    if (idr2 != null)
                    {
                        idr2.Close();
                    }
                    log.Log(Level.SEVERE, SQL, ept);
                }
                finally
                {
                    if (idr2 != null)
                    {
                        idr2.Close();
                    }
                    dt = null;
                }

                //Load Cash Books
                SQL = MRole.GetDefault().AddAccessSQL(
                    "SELECT C_CashBook_ID, Name, AD_Org_ID FROM C_CashBook WHERE IsActive='Y'",
                    "C_CashBook", MRole.SQL_NOTQUALIFIED, MRole.SQL_RO);
                kp = null;
                IDataReader idr3 = null;
                try
                {

                    idr3 = DB.ExecuteReader(SQL, null, null);
                    dt = new DataTable();
                    dt.Load(idr3);
                    idr3.Close();
                    foreach (DataRow dr in dt.Rows)
                    {
                        int key = Util.GetValueOfInt(dr[0]);// dr.getInt(1);
                        String name = dr[1].ToString();//.getString(2);
                        KeyNamePair pp = new KeyNamePair(key, name);
                        //cmbBCashBook.Items.Add(pp);
                        loadCashBooks.Add(pp);
                        if (key == _C_CashBook_ID)
                        {
                            kp = pp;
                        }
                        if (kp == null && key == _AD_Org_ID)       //  Default Org
                        {
                            kp = pp;
                        }
                    }

                }
                catch (Exception epc)
                {
                    if (idr3 != null)
                    {
                        idr3.Close();
                    }
                    log.Log(Level.SEVERE, SQL, epc);
                }
                finally
                {
                    if (idr3 != null)
                    {
                        idr3.Close();
                    }
                    dt = null;
                }



                Deployment.Current.Dispatcher.BeginInvoke
           (delegate
           {
               //centerPanel.Visibility = !_onlyRule;
               if (!_onlyRule)
               {
                   centerPanel.Visibility = System.Windows.Visibility.Collapsed;
               }
               else
               {
                   centerPanel.Visibility = System.Windows.Visibility.Visible;
               }

               //if (centerPanel.Visibility = !_onlyRule)
               //{
               //    centerPanel.Size = new System.Drawing.Size(316, 74);
               //    this.ClientSize = new System.Drawing.Size(400, 250);
               //}
               //else
               //{
               //    this.ClientSize = new System.Drawing.Size(290, 100);
               //}
               lblBAmountField.Content = _Amount.ToString();
               lblSAmountField.Content = _Amount.ToString();


               txtKNumber.Text = strKNumber;
               txtKExp.Text = strKExp;
               txtKApproval.Text = strKApproval;
               lblKStatus.Content = strKStatus;

               if (canChange)
               {
                   cmbKType.IsEnabled = true;
                   txtKNumber.IsEnabled = true;
                   txtKExp.IsEnabled = true;
                   txtKApproval.IsEnabled = true;
                   btnKOnline.IsEnabled = true;
               }

               txtSRouting.Text = strSRouting;
               txtSNumber.Text = strSNumber;
               txtSCheck.Text = strSCheck;
               lblSStatus.Content = strSStatus;
               //  Transfer
               lblTStatus.Content = strTStatus;

               //	Accounting Date
               bDateField.Value = _DateAcct.Value.Date;

               //	Is the currency an EMU currency?
               int C_Currency_ID = _C_Currency_ID;
               if (_Currencies != null && _Currencies.ContainsKey(C_Currency_ID))
               {
                   IEnumerator en = (IEnumerator)_Currencies.Keys.GetEnumerator();
                   while (en.MoveNext())
                   {
                       Object key = en.Current;
                       cmbBCurrency.Items.Add(_Currencies[(int)key]);
                       cmbSCurrency.Items.Add(_Currencies[(int)key]);
                   }
                   cmbSCurrency.SelectedItem = _Currencies[C_Currency_ID];
                   cmbBCurrency.SelectedItem = _Currencies[C_Currency_ID];
               }
               else	//	No EMU Currency
               {
                   lblBCurrencyLabel.Visibility = System.Windows.Visibility.Collapsed;	//	Cash
                   cmbBCurrency.Visibility = System.Windows.Visibility.Collapsed;
                   lblSCurrencyLabel.Visibility = System.Windows.Visibility.Collapsed;	//	Check
                   cmbSCurrency.Visibility = System.Windows.Visibility.Collapsed;
               }


               //Payment Combo
               if (_PaymentRule == null)
               {
                   _PaymentRule = "";
               }
               //Add items in the Payment combo(cmbPayment)

               //HashMap values = button.GetValues();
               // Dictionary<String, String> values = button.GetValues();
               //Object[] a = values.keySet().toArray();
               Object[] a = values.Keys.ToArray();
               for (int i = 0; i < a.Length; i++)
               {
                   String PaymentRule = (String)a[i];		//	used for Panel selection
                   if (X_C_Order.PAYMENTRULE_DirectDebit.Equals(PaymentRule)			//	SO
                       && !_isSOTrx)
                   {
                       continue;
                   }
                   else if (X_C_Order.PAYMENTRULE_DirectDeposit.Equals(PaymentRule)	//	PO 
                       && _isSOTrx)
                   {
                       continue;
                   }
                   //ValueNamePair pp = new ValueNamePair(PaymentRule, (String)values.get(a[i]));
                   ValueNamePair pp = new ValueNamePair(PaymentRule, (String)values[a[i].ToString()]);
                   cmbPayment.Items.Add(pp);
                   if (PaymentRule.ToString().Equals(_PaymentRule))	//	to select
                   {
                       vp = pp;
                   }
               }

               //	Set PaymentRule
               // this.tblpMain.Controls.Add(this.cmbPayment, 1, 0);
               this.grdUp.Children.Add(cmbPayment);
               cmbPayment.Margin = new Thickness(3);
               Grid.SetColumn(cmbPayment, 1);
               Grid.SetRow(cmbPayment, 0);


               if (vp != null)
               {
                   //cmbPayment.setSelectedItem(vp);
                   cmbPayment.SelectedItem = vp;
               }

               //Load Payment Terms
               for (int i = 0; i < loadPaymentTerms.Count; i++)
               {
                   cmbPTerm.Items.Add(loadPaymentTerms[i]);
               }

               //	Set Selection
               if (kp != null)
               {
                   cmbPTerm.SelectedItem = kp;
               }

               //Load Accounts
               for (int i = 0; i < loadAccounts.Count; i++)
               {
                   cmbTAccount.Items.Add(loadAccounts[i]);
               }
               //	Set Selection
               if (kp != null)
               {
                   cmbTAccount.SelectedItem = kp;
               }

               //Load Credit Cards
               vp = null;
               for (int i = 0; i < ccs.Length; i++)
               {
                   cmbKType.Items.Add(ccs[i]);
                   if (ccs[i].GetValue().Equals(_CCType))
                   {
                       vp = ccs[i];
                   }
               }
               //	Set Selection
               if (vp != null)
               {
                   cmbKType.SelectedItem = vp;
               }

               //Load Bank Accounts
               for (int i = 0; i < loadBankAccounts.Count; i++)
               {
                   cmbSBankAccount.Items.Add(loadBankAccounts[i]);
               }
               //	Set Selection
               if (kp != null)
               {
                   cmbSBankAccount.SelectedItem = kp;
               }

               //Load Cash Books
               for (int i = 0; i < loadCashBooks.Count; i++)
               {
                   cmbBCashBook.Items.Add(loadCashBooks[i]);
               }
               //	Set Selection
               if (kp != null)
               {
                   cmbBCashBook.SelectedItem = kp;
                   if (_C_CashBook_ID == 0)
                   {
                       _C_CashBook_ID = kp.GetKey();  //  set to default to avoid 'cashbook changed' message
                   }
               }

               if (_PaymentRule == "B")
               {
                   this.kPanel.Visibility = System.Windows.Visibility.Collapsed;
                   this.pPanel.Visibility = System.Windows.Visibility.Collapsed;
                   this.bPanel.Visibility = System.Windows.Visibility.Visible;
                   this.tPanel.Visibility = System.Windows.Visibility.Collapsed;
                   this.sPanel.Visibility = System.Windows.Visibility.Collapsed;
               }
               else if (_PaymentRule == "K")
               {
                   this.kPanel.Visibility = System.Windows.Visibility.Visible;
                   this.pPanel.Visibility = System.Windows.Visibility.Collapsed;
                   this.bPanel.Visibility = System.Windows.Visibility.Collapsed;
                   this.tPanel.Visibility = System.Windows.Visibility.Collapsed;
                   this.sPanel.Visibility = System.Windows.Visibility.Collapsed;
               }
               else if (_PaymentRule == "D")
               {
                   this.kPanel.Visibility = System.Windows.Visibility.Collapsed;
                   this.pPanel.Visibility = System.Windows.Visibility.Collapsed;
                   this.bPanel.Visibility = System.Windows.Visibility.Collapsed;
                   this.tPanel.Visibility = System.Windows.Visibility.Visible;
                   this.sPanel.Visibility = System.Windows.Visibility.Collapsed;
               }
               else if (_PaymentRule == "P")
               {
                   this.kPanel.Visibility = System.Windows.Visibility.Collapsed;
                   this.pPanel.Visibility = System.Windows.Visibility.Visible;
                   this.bPanel.Visibility = System.Windows.Visibility.Collapsed;
                   this.tPanel.Visibility = System.Windows.Visibility.Collapsed;
                   this.sPanel.Visibility = System.Windows.Visibility.Collapsed;
               }
               else if (_PaymentRule == "S")
               {
                   this.kPanel.Visibility = System.Windows.Visibility.Collapsed;
                   this.pPanel.Visibility = System.Windows.Visibility.Collapsed;
                   this.bPanel.Visibility = System.Windows.Visibility.Collapsed;
                   this.tPanel.Visibility = System.Windows.Visibility.Collapsed;
                   this.sPanel.Visibility = System.Windows.Visibility.Visible;
               }

           });
            }
            catch (Exception e)
            {
                log.Log(Level.SEVERE, "", e);
                //MessageBox.Show(e.ToString());
            }
            return true;
        }

        //private bool DynInit(Dictionary<String, String> values)
        //{
        //    try
        //    {
        //        _DocStatus = (String)_mTab.GetValue("DocStatus");
        //        log.Config(_DocStatus);

        //        if (_mTab.GetValue("C_BPartner_ID") == null)
        //        {
        //            ShowMessage.Error("0", true, Msg.GetMsg(Envs.GetContext(), "SaveErrorRowNotFound", true));
        //            return false;
        //        }

        //        //  DocStatus
        //        _DocStatus = (String)_mTab.GetValue("DocStatus");
        //        if (_DocStatus == null)
        //        {
        //            _DocStatus = "";
        //        }
        //        //	Is the Trx closed?		Reversed / Voided / Cloased
        //        if (_DocStatus.Equals("RE") || _DocStatus.Equals("VO") || _DocStatus.Equals("CL"))
        //        {
        //            return false;
        //        }
        //        //  Document is not complete - allow to change the Payment Rule only
        //        if (_DocStatus.Equals("CO") || _DocStatus.Equals("WP"))
        //        {
        //            _onlyRule = false;
        //        }
        //        else
        //        {
        //            _onlyRule = true;
        //        }
        //        //	PO only  Rule
        //        if (!_onlyRule		//	Only order has Warehouse
        //            && !_isSOTrx && _mTab.GetValue("M_Warehouse_ID") != null)
        //        {
        //            _onlyRule = true;
        //        }

        //        //centerPanel.Visibility = !_onlyRule;
        //        if (!_onlyRule)
        //        {
        //            centerPanel.Visibility = System.Windows.Visibility.Collapsed;
        //        }
        //        else
        //        {
        //            centerPanel.Visibility = System.Windows.Visibility.Visible;
        //        }

        //        //if (centerPanel.Visibility = !_onlyRule)
        //        //{
        //        //    centerPanel.Size = new System.Drawing.Size(316, 74);
        //        //    this.ClientSize = new System.Drawing.Size(400, 250);
        //        //}
        //        //else
        //        //{
        //        //    this.ClientSize = new System.Drawing.Size(290, 100);
        //        //}

        //        //  Amount
        //        _Amount = (Decimal)_mTab.GetValue("GrandTotal");
        //        if (!_onlyRule && _Amount.CompareTo(Envs.ZERO) == 0)
        //        {
        //            //ADialog.error(m_WindowNo, this, "PaymentZero");
        //            ShowMessage.Error("", true, Msg.GetMsg(Envs.GetContext(), "PaymentZero", true));
        //            return false;
        //        }
        //        lblBAmountField.Content = _Amount.ToString();
        //        lblSAmountField.Content = _Amount.ToString();

        //        //Get Data from Grid
        //        _AD_Client_ID = Convert.ToInt32(_mTab.GetValue("AD_Client_ID"));//.intValue();
        //        _AD_Client_ID = Convert.ToInt32(_mTab.GetValue("AD_Client_ID"));
        //        _AD_Org_ID = Convert.ToInt32(_mTab.GetValue("AD_Org_ID"));//.intValue();
        //        _C_BPartner_ID = Convert.ToInt32(_mTab.GetValue("C_BPartner_ID"));//.intValue();
        //        _PaymentRule = (String)_mTab.GetValue("PaymentRule");
        //        _C_Currency_ID = Convert.ToInt32(_mTab.GetValue("C_Currency_ID"));//.intValue();
        //        _DateAcct = Convert.ToDateTime(_mTab.GetValue("DateAcct"));

        //        if (_mTab.GetValue("C_PaymentTerm_ID") != null || _mTab.GetValue("C_PaymentTerm_ID") != DBNull.Value)
        //        {
        //            _C_PaymentTerm_ID = Convert.ToInt32(_mTab.GetValue("C_PaymentTerm_ID"));//.intValue();
        //        }
        //        //  Existing Payment
        //        if (_mTab.GetValue("C_Payment_ID") != null && _mTab.GetValue("C_Payment_ID") != DBNull.Value)
        //        {
        //            _C_Payment_ID = Util.GetValueOfInt(_mTab.GetValue("C_Payment_ID"));//.intValue();
        //            if (_C_Payment_ID != 0)
        //            {
        //                _mPayment = new MPayment(Envs.GetContext(), _C_Payment_ID, null);
        //                _mPaymentOriginal = new MPayment(Envs.GetContext(), _C_Payment_ID, null);	//	full copy
        //                //  CreditCard
        //                _CCType = _mPayment.GetCreditCardType();
        //                txtKNumber.Text = _mPayment.GetCreditCardNumber();
        //                txtKExp.Text = _mPayment.GetCreditCardExp(null);
        //                txtKApproval.Text = _mPayment.GetVoiceAuthCode();
        //                lblKStatus.Content = _mPayment.GetR_PnRef();
        //                bool canChange = !_mPayment.IsApproved() || !(_PaymentRule == MOrder.PAYMENTRULE_CreditCard);
        //                //	if approved/paid, don't let it change
        //                if (canChange)
        //                {
        //                    cmbKType.IsEnabled = true;
        //                    txtKNumber.IsEnabled = true;
        //                    txtKExp.IsEnabled = true;
        //                    txtKApproval.IsEnabled = true;
        //                    btnKOnline.IsEnabled = true;
        //                }
        //                //  Check
        //                _C_BankAccount_ID = _mPayment.GetC_BankAccount_ID();
        //                txtSRouting.Text = _mPayment.GetRoutingNo();
        //                txtSNumber.Text = _mPayment.GetAccountNo();
        //                txtSCheck.Text = _mPayment.GetCheckNo();
        //                lblSStatus.Content = _mPayment.GetR_PnRef();
        //                //  Transfer
        //                lblTStatus.Content = _mPayment.GetR_PnRef();
        //            }
        //        }
        //        if (_mPayment == null)
        //        {
        //            _mPayment = new MPayment(Envs.GetContext(), 0, null);
        //            _mPayment.SetAD_Org_ID(_AD_Org_ID);
        //            _mPayment.SetIsReceipt(_isSOTrx);
        //            _mPayment.SetAmount(_C_Currency_ID, _Amount);
        //        }

        //        //  Existing Cahbook entry
        //        _cashLine = null;
        //        _C_CashLine_ID = 0;
        //        if (_mTab.GetValue("C_CashLine_ID") != null && _mTab.GetValue("C_CashLine_ID") != DBNull.Value)
        //        {
        //            _C_CashLine_ID = Convert.ToInt32(_mTab.GetValue("C_CashLine_ID"));//.intValue();
        //            if (_C_CashLine_ID == 0)
        //            {
        //                _cashLine = null;
        //            }
        //            else
        //            {
        //                _cashLine = new MCashLine(Envs.GetContext(), _C_CashLine_ID, null);
        //                _DateAcct = _cashLine.GetStatementDate();
        //            }
        //        }

        //        //	Accounting Date
        //        bDateField.Value = _DateAcct.Value.Date;

        //        if (_Currencies == null)
        //        {
        //            LoadCurrencies();
        //        }

        //        //	Is the currency an EMU currency?
        //        int C_Currency_ID = _C_Currency_ID;
        //        if (_Currencies != null && _Currencies.ContainsKey(C_Currency_ID))
        //        {
        //            IEnumerator en = (IEnumerator)_Currencies.Keys.GetEnumerator();
        //            while (en.MoveNext())
        //            {
        //                Object key = en.Current;
        //                cmbBCurrency.Items.Add(_Currencies[(int)key]);
        //                cmbSCurrency.Items.Add(_Currencies[(int)key]);
        //            }
        //            cmbSCurrency.SelectedItem = _Currencies[C_Currency_ID];
        //            cmbBCurrency.SelectedItem = _Currencies[C_Currency_ID];
        //        }
        //        else	//	No EMU Currency
        //        {
        //            lblBCurrencyLabel.Visibility = System.Windows.Visibility.Collapsed;	//	Cash
        //            cmbBCurrency.Visibility = System.Windows.Visibility.Collapsed;
        //            lblSCurrencyLabel.Visibility = System.Windows.Visibility.Collapsed;	//	Check
        //            cmbSCurrency.Visibility = System.Windows.Visibility.Collapsed;
        //        }

        //        //Payment Combo
        //        if (_PaymentRule == null)
        //        {
        //            _PaymentRule = "";
        //        }
        //        //Add items in the Payment combo(cmbPayment)
        //        ValueNamePair vp = null;
        //        //HashMap values = button.GetValues();
        //        // Dictionary<String, String> values = button.GetValues();
        //        //Object[] a = values.keySet().toArray();
        //        Object[] a = values.Keys.ToArray();
        //        for (int i = 0; i < a.Length; i++)
        //        {
        //            String PaymentRule = (String)a[i];		//	used for Panel selection
        //            if (X_C_Order.PAYMENTRULE_DirectDebit.Equals(PaymentRule)			//	SO
        //                && !_isSOTrx)
        //            {
        //                continue;
        //            }
        //            else if (X_C_Order.PAYMENTRULE_DirectDeposit.Equals(PaymentRule)	//	PO 
        //                && _isSOTrx)
        //            {
        //                continue;
        //            }
        //            //ValueNamePair pp = new ValueNamePair(PaymentRule, (String)values.get(a[i]));
        //            ValueNamePair pp = new ValueNamePair(PaymentRule, (String)values[a[i].ToString()]);
        //            cmbPayment.Items.Add(pp);
        //            if (PaymentRule.ToString().Equals(_PaymentRule))	//	to select
        //            {
        //                vp = pp;
        //            }
        //        }

        //        //	Set PaymentRule
        //        // this.tblpMain.Controls.Add(this.cmbPayment, 1, 0);
        //        this.grdUp.Children.Add(cmbPayment);
        //        cmbPayment.Margin = new Thickness(3);
        //        Grid.SetColumn(cmbPayment, 1);
        //        Grid.SetRow(cmbPayment, 0);


        //        if (vp != null)
        //        {
        //            //cmbPayment.setSelectedItem(vp);
        //            cmbPayment.SelectedItem = vp;
        //        }

        //        //Load Payment Terms
        //        String SQL = MRole.GetDefault().AddAccessSQL(
        //            "SELECT C_PaymentTerm_ID, Name FROM C_PaymentTerm WHERE IsActive='Y' ORDER BY Name",
        //            "C_PaymentTerm", MRole.SQL_NOTQUALIFIED, MRole.SQL_RO);
        //        KeyNamePair kp = null;
        //        IDataReader idr = null;
        //        DataTable dt = null;
        //        try
        //        {

        //            idr = DB.ExecuteReader(SQL, null, null);
        //            dt = new DataTable();
        //            dt.Load(idr);
        //            idr.Close();
        //            foreach (DataRow dr in dt.Rows)
        //            {
        //                int key = Util.GetValueOfInt(dr[0]);//.getInt(1);
        //                String name = dr[1].ToString();//.getString(2);
        //                KeyNamePair pp = new KeyNamePair(key, name);
        //                cmbPTerm.Items.Add(pp);
        //                if (key == _C_PaymentTerm_ID)
        //                {
        //                    kp = pp;
        //                }
        //            }

        //        }
        //        catch (Exception ept)
        //        {
        //            if (idr != null)
        //            {
        //                idr.Close();
        //            }
        //            log.Log(Level.SEVERE, SQL, ept);
        //        }
        //        finally
        //        {
        //            if (idr != null)
        //            {
        //                idr.Close();
        //            }
        //            dt = null;
        //        }
        //        //	Set Selection
        //        if (kp != null)
        //        {
        //            cmbPTerm.SelectedItem = kp;
        //        }

        //        //Load Accounts
        //        SQL = "SELECT a.C_BP_BankAccount_ID, NVL(b.Name, ' ')||a.AccountNo AS Acct "
        //            + "FROM C_BP_BankAccount a,C_Bank b "
        //            + "WHERE C_BPartner_ID=" + _C_BPartner_ID + " AND a.IsActive='Y'";
        //        kp = null;
        //        IDataReader idr1 = null;
        //        try
        //        {

        //            idr1 = DB.ExecuteReader(SQL, null, null);
        //            dt = new DataTable();
        //            dt.Load(idr1);
        //            idr1.Close();
        //            foreach (DataRow dr in dt.Rows)
        //            {
        //                int key = Util.GetValueOfInt(dr[0]);// dr.getInt(1);
        //                String name = dr[1].ToString();//.getString(2);
        //                KeyNamePair pp = new KeyNamePair(key, name);
        //                cmbTAccount.Items.Add(pp);
        //                /*			kp = pp;*/
        //            }

        //        }
        //        catch (Exception eac)
        //        {
        //            if (idr1 != null)
        //            {
        //                idr1.Close();
        //            }
        //            log.Log(Level.SEVERE, SQL, eac);
        //        }
        //        finally
        //        {
        //            if (idr1 != null)
        //            {
        //                idr1.Close();
        //            }
        //            dt = null;
        //        }
        //        //	Set Selection
        //        if (kp != null)
        //        {
        //            cmbTAccount.SelectedItem = kp;
        //        }

        //        //Load Credit Cards
        //        ValueNamePair[] ccs = _mPayment.GetCreditCards();
        //        vp = null;
        //        for (int i = 0; i < ccs.Length; i++)
        //        {
        //            cmbKType.Items.Add(ccs[i]);
        //            if (ccs[i].GetValue().Equals(_CCType))
        //            {
        //                vp = ccs[i];
        //            }
        //        }
        //        //	Set Selection
        //        if (vp != null)
        //        {
        //            cmbKType.SelectedItem = vp;
        //        }

        //        //Load Bank Accounts
        //        SQL = MRole.GetDefault().AddAccessSQL(
        //            "SELECT C_BankAccount_ID, Name || ' ' || AccountNo, IsDefault "
        //            + "FROM C_BankAccount ba"
        //            + " INNER JOIN C_Bank b ON (ba.C_Bank_ID=b.C_Bank_ID) "
        //            + "WHERE b.IsActive='Y'",
        //            "ba", MRole.SQL_FULLYQUALIFIED, MRole.SQL_RO);
        //        kp = null;
        //        IDataReader idr2 = null;
        //        try
        //        {

        //            idr2 = DB.ExecuteReader(SQL, null, null);
        //            dt = new DataTable();
        //            dt.Load(idr2);
        //            idr2.Close();
        //            foreach (DataRow dr in dt.Rows)
        //            {
        //                int key = Util.GetValueOfInt(dr[0]);// dr.getInt(1);
        //                String name = dr[1].ToString();//.getString(2);
        //                KeyNamePair pp = new KeyNamePair(key, name);
        //                cmbSBankAccount.Items.Add(pp);
        //                if (key == _C_BankAccount_ID)
        //                {
        //                    kp = pp;
        //                }
        //                if (kp == null && dr[2].ToString().Equals("Y"))    //  Default
        //                {
        //                    kp = pp;
        //                }
        //            }

        //        }
        //        catch (Exception ept)
        //        {
        //            if (idr2 != null)
        //            {
        //                idr2.Close();
        //            }
        //            log.Log(Level.SEVERE, SQL, ept);
        //        }
        //        finally
        //        {
        //            if (idr2 != null)
        //            {
        //                idr2.Close();
        //            }
        //            dt = null;
        //        }
        //        //	Set Selection
        //        if (kp != null)
        //        {
        //            cmbSBankAccount.SelectedItem = kp;
        //        }


        //        //Load Cash Books
        //        SQL = MRole.GetDefault().AddAccessSQL(
        //            "SELECT C_CashBook_ID, Name, AD_Org_ID FROM C_CashBook WHERE IsActive='Y'",
        //            "C_CashBook", MRole.SQL_NOTQUALIFIED, MRole.SQL_RO);
        //        kp = null;
        //        IDataReader idr3 = null;
        //        try
        //        {

        //            idr3 = DB.ExecuteReader(SQL, null, null);
        //            dt = new DataTable();
        //            dt.Load(idr3);
        //            idr3.Close();
        //            foreach (DataRow dr in dt.Rows)
        //            {
        //                int key = Util.GetValueOfInt(dr[0]);// dr.getInt(1);
        //                String name = dr[1].ToString();//.getString(2);
        //                KeyNamePair pp = new KeyNamePair(key, name);
        //                cmbBCashBook.Items.Add(pp);
        //                if (key == _C_CashBook_ID)
        //                {
        //                    kp = pp;
        //                }
        //                if (kp == null && key == _AD_Org_ID)       //  Default Org
        //                {
        //                    kp = pp;
        //                }
        //            }

        //        }
        //        catch (Exception epc)
        //        {
        //            if (idr3 != null)
        //            {
        //                idr3.Close();
        //            }
        //            log.Log(Level.SEVERE, SQL, epc);
        //        }
        //        finally
        //        {
        //            if (idr3 != null)
        //            {
        //                idr3.Close();
        //            }
        //            dt = null;
        //        }
        //        //	Set Selection
        //        if (kp != null)
        //        {
        //            cmbBCashBook.SelectedItem = kp;
        //            if (_C_CashBook_ID == 0)
        //            {
        //                _C_CashBook_ID = kp.GetKey();  //  set to default to avoid 'cashbook changed' message
        //            }
        //        }
        //        if (_PaymentRule == "B")
        //        {
        //            this.kPanel.Visibility = System.Windows.Visibility.Collapsed;
        //            this.pPanel.Visibility = System.Windows.Visibility.Collapsed;
        //            this.bPanel.Visibility = System.Windows.Visibility.Visible;
        //            this.tPanel.Visibility = System.Windows.Visibility.Collapsed;
        //            this.sPanel.Visibility = System.Windows.Visibility.Collapsed;
        //        }
        //        else if (_PaymentRule == "K")
        //        {
        //            this.kPanel.Visibility = System.Windows.Visibility.Visible;
        //            this.pPanel.Visibility = System.Windows.Visibility.Collapsed;
        //            this.bPanel.Visibility = System.Windows.Visibility.Collapsed;
        //            this.tPanel.Visibility = System.Windows.Visibility.Collapsed;
        //            this.sPanel.Visibility = System.Windows.Visibility.Collapsed;
        //        }
        //        else if (_PaymentRule == "D")
        //        {
        //            this.kPanel.Visibility = System.Windows.Visibility.Collapsed;
        //            this.pPanel.Visibility = System.Windows.Visibility.Collapsed;
        //            this.bPanel.Visibility = System.Windows.Visibility.Collapsed;
        //            this.tPanel.Visibility = System.Windows.Visibility.Visible;
        //            this.sPanel.Visibility = System.Windows.Visibility.Collapsed;
        //        }
        //        else if (_PaymentRule == "P")
        //        {
        //            this.kPanel.Visibility = System.Windows.Visibility.Collapsed;
        //            this.pPanel.Visibility = System.Windows.Visibility.Visible;
        //            this.bPanel.Visibility = System.Windows.Visibility.Collapsed;
        //            this.tPanel.Visibility = System.Windows.Visibility.Collapsed;
        //            this.sPanel.Visibility = System.Windows.Visibility.Collapsed;
        //        }
        //        else if (_PaymentRule == "S")
        //        {
        //            this.kPanel.Visibility = System.Windows.Visibility.Collapsed;
        //            this.pPanel.Visibility = System.Windows.Visibility.Collapsed;
        //            this.bPanel.Visibility = System.Windows.Visibility.Collapsed;
        //            this.tPanel.Visibility = System.Windows.Visibility.Collapsed;
        //            this.sPanel.Visibility = System.Windows.Visibility.Visible;
        //        }
        //    }
        //    catch (Exception e)
        //    {
        //        log.Log(Level.SEVERE, "", e);
        //        //MessageBox.Show(e.ToString());
        //    }
        //    return true;
        //}

        /// <summary>
        /// Init OK to be able to make changes?
        /// </summary>
        /// <returns>true if init OK</returns>
        public bool IsInitOK()
        {
            return _initOK;
        }

        /// <summary>
        /// Fill _Currencies with EMU currencies
        /// </summary>
        private void LoadCurrencies()
        {
            //_Currencies = new Hashtable<Integer, KeyNamePair>(12);	//	Currenly only 10+1
            _Currencies = new Dictionary<int, KeyNamePair>();	//	Currenly only 10+1
            String SQL = "SELECT C_Currency_ID, ISO_Code FROM C_Currency "
                + "WHERE (IsEMUMember='Y' AND EMUEntryDate<SysDate) OR IsEuro='Y' "
                + "ORDER BY 2";
            DataTable dt = null;
            IDataReader idr = null;
            try
            {

                idr = DB.ExecuteReader(SQL, null, null);
                dt = new DataTable();
                dt.Load(idr);
                idr.Close();
                foreach (DataRow dr in dt.Rows)
                {
                    int id = Util.GetValueOfInt(dr[0]);//.getInt(1);
                    String name = dr[1].ToString();//.getString(2);
                    _Currencies.Add(id, new KeyNamePair(id, name));
                }

            }
            catch (Exception e)
            {
                if (idr != null)
                {
                    idr.Close();
                }
                log.Log(Level.SEVERE, SQL, e);
            }
            finally
            {
                if (idr != null)
                {
                    idr.Close();
                }
                dt = null;
            }
        }

        public bool btnTextChange = false;
        /// <summary>
        /// Save Changes
        /// </summary>
        /// <returns>true, if eindow can exit</returns>
        private bool SaveChanges()
        {
            try
            {
                ValueNamePair vp = (ValueNamePair)cmbPayment.SelectedItem;
                String newPaymentRule = vp.GetValue();
                log.Info("New Rule: " + newPaymentRule);

                //  only Payment Rule
                if (_onlyRule)
                {
                    if (!newPaymentRule.Equals(_PaymentRule))
                    {
                        btnTextChange = true;
                        _mTab.SetValue("PaymentRule", newPaymentRule);
                    }
                    return true;
                }

                //	New Values
                DateTime? newDateAcct = _DateAcct;
                int newC_PaymentTerm_ID = _C_PaymentTerm_ID;
                int newC_CashLine_ID = _C_CashLine_ID;
                int newC_CashBook_ID = _C_CashBook_ID;
                String newCCType = _CCType;
                int newC_BankAccount_ID = 0;

                //	B (Cash)		(Currency)
                if (newPaymentRule.Equals(X_C_Order.PAYMENTRULE_Cash))
                {
                    KeyNamePair kp = (KeyNamePair)cmbBCashBook.SelectedItem;
                    if (kp != null)
                    {
                        newC_CashBook_ID = kp.GetKey();
                    }
                    //newDateAcct = (DateTime)bDateField.GetValue();
                    newDateAcct = (DateTime)bDateField.Value;
                }

                //	K (CreditCard)  Type, Number, Exp, Approval
                else if (newPaymentRule.Equals(X_C_Order.PAYMENTRULE_CreditCard))
                {
                    vp = (ValueNamePair)cmbKType.SelectedItem;
                    if (vp != null)
                    {
                        newCCType = vp.GetValue();
                    }
                }

                //	T (Transfer)	BPartner_Bank
                else if (newPaymentRule.Equals(MOrder.PAYMENTRULE_DirectDeposit)
                    || newPaymentRule.Equals(MOrder.PAYMENTRULE_DirectDebit))
                {
                    KeyNamePair myObj = (KeyNamePair)cmbTAccount.SelectedItem;
                }

                //	P (PaymentTerm)	PaymentTerm
                else if (newPaymentRule.Equals(X_C_Order.PAYMENTRULE_OnCredit))
                {
                    KeyNamePair kp = (KeyNamePair)cmbPTerm.SelectedItem;
                    if (kp != null)
                    {
                        newC_PaymentTerm_ID = kp.GetKey();
                    }
                }

                //	S (Check)		(Currency) CheckNo, Routing
                else if (newPaymentRule.Equals(X_C_Order.PAYMENTRULE_Check))
                {
                    //	cmbSCurrency.SelectedItem;
                    KeyNamePair kp = (KeyNamePair)cmbSBankAccount.SelectedItem;
                    if (kp != null)
                    {
                        newC_BankAccount_ID = kp.GetKey();
                    }
                }
                else
                {
                    return false;
                }

                //  find Bank Account if not qualified yet
                if ("KTSD".IndexOf(newPaymentRule) != -1 && newC_BankAccount_ID == 0)
                {
                    String tender = MPayment.TENDERTYPE_CreditCard;
                    if (newPaymentRule.Equals(MOrder.PAYMENTRULE_DirectDeposit))
                    {
                        tender = MPayment.TENDERTYPE_DirectDeposit;
                    }
                    else if (newPaymentRule.Equals(MOrder.PAYMENTRULE_DirectDebit))
                    {
                        tender = MPayment.TENDERTYPE_DirectDebit;
                    }
                    else if (newPaymentRule.Equals(MOrder.PAYMENTRULE_Check))
                    {
                        tender = MPayment.TENDERTYPE_Check;
                    }
                }

                /***********************
                 *  Changed PaymentRule
                 */
                if (!newPaymentRule.Equals(_PaymentRule))
                {
                    //log.fine("Changed PaymentRule: " + _PaymentRule + " -> " + newPaymentRule);
                    //  We had a CashBook Entry
                    if (_PaymentRule.Equals(X_C_Order.PAYMENTRULE_Cash))
                    {
                        //log.fine("Old Cash - " + _cashLine);
                        if (_cashLine != null)
                        {
                            MCashLine cl = _cashLine.CreateReversal();
                            if (cl.Save())
                            {
                                log.Config("CashCancelled");
                                //MessageBox.Show("CashCancelled");
                            }
                            else
                            {
                                ShowMessage.Error("", true, "PaymentError" + Msg.GetMsg(Envs.GetContext(), "CashNotCancelled", true).ToString());
                            }
                        }
                        newC_CashLine_ID = 0;      //  reset
                    }
                    //  We had a change in Payment type (e.g. Check to CC)
                    else if ("KTSD".IndexOf(_PaymentRule) != -1 && "KTSD".IndexOf(newPaymentRule) != -1 && _mPaymentOriginal != null)
                    {
                        //log.fine("Old Payment(1) - " + _mPaymentOriginal);
                        _mPaymentOriginal.SetDocAction(DocActionVariables.ACTION_REVERSE_CORRECT);
                        bool ok = _mPaymentOriginal.ProcessIt(DocActionVariables.ACTION_REVERSE_CORRECT);
                        _mPaymentOriginal.Save();
                        if (ok)
                        {
                            log.Info("Payment Canecelled - " + _mPaymentOriginal);
                        }
                        else
                        {
                            ShowMessage.Error("", true, "PaymentError" + Msg.GetMsg(Envs.GetContext(), "PaymentNotCancelled", true).ToString() + _mPaymentOriginal.GetDocumentNo());
                        }
                        _mPayment.ReSetNew();
                    }
                    //	We had a Payment and something else (e.g. Check to Cash)
                    else if ("KTSD".IndexOf(_PaymentRule) != -1 && "KTSD".IndexOf(newPaymentRule) == -1)
                    {
                        //log.fine("Old Payment(2) - " + _mPaymentOriginal);
                        if (_mPaymentOriginal != null)
                        {
                            _mPaymentOriginal.SetDocAction(DocActionVariables.ACTION_REVERSE_CORRECT);
                            bool ok = _mPaymentOriginal.ProcessIt(DocActionVariables.ACTION_REVERSE_CORRECT);
                            _mPaymentOriginal.Save();
                            if (ok)        //  Cancel Payment
                            {
                                log.Fine("PaymentCancelled " + _mPayment.GetDocumentNo());
                                //_mTab.getTableModel().dataSave(true);
                                DataRow datarow = null;
                                _mTab.GetTableObj().DataSave(true, datarow);//**********************************2nd parameter
                                _mPayment.ReSetNew();
                                _mPayment.SetAmount(_C_Currency_ID, _Amount);
                            }
                            else
                            {
                                ShowMessage.Error("", true, "PaymentError" + Msg.GetMsg(Envs.GetContext(), "PaymentNotCancelled", true).ToString() + _mPayment.GetDocumentNo());
                            }
                        }
                    }
                }

                //  Get Order and optionally Invoice
                int C_Order_ID = Envs.GetContext().GetContextAsInt(_WindowNo, "C_Order_ID");
                int C_Invoice_ID = Envs.GetContext().GetContextAsInt(_WindowNo, "C_Invoice_ID");
                if (C_Invoice_ID == 0 && _DocStatus.Equals("CO"))
                {
                    C_Invoice_ID = GetInvoiceID(C_Order_ID);
                }
                //  Amount sign negative, if ARC (Credit Memo) or API (AP Invoice)
                bool negateAmt = false;
                MInvoice invoice = null;
                if (C_Invoice_ID != 0)
                {
                    invoice = new MInvoice(Envs.GetContext(), C_Invoice_ID, null);
                    negateAmt = invoice.IsCreditMemo();
                }
                MOrder order = null;
                if (invoice == null && C_Order_ID != 0)
                {
                    order = new MOrder(Envs.GetContext(), C_Order_ID, null);
                }
                Decimal payAmount = _Amount;
                if (negateAmt)
                {
                    payAmount = Decimal.Negate(_Amount);//.negate();
                }
                // Info
                log.Config("C_Order_ID=" + C_Order_ID + ", C_Invoice_ID=" + C_Invoice_ID + ", NegateAmt=" + negateAmt);

                /***********************
                 *  CashBook
                 */
                if (newPaymentRule.Equals(X_C_Order.PAYMENTRULE_Cash))
                {
                    //log.fine("Cash");
                    String description = (String)_mTab.GetValue("DocumentNo");

                    if (C_Invoice_ID == 0 && order == null)
                    {
                        log.Config("No Invoice!");
                        ShowMessage.Error("", true, "PaymentError" + Msg.GetMsg(Envs.GetContext(), "CashNotCreated", true).ToString());
                    }
                    else
                    {
                        //  Changed Amount
                        if (_cashLine != null
                            && payAmount.CompareTo(_cashLine.GetAmount()) != 0)
                        {
                            log.Config("Changed CashBook Amount");
                            _cashLine.SetAmount(payAmount);
                            if (_cashLine.Save())
                            {
                                log.Config("CashAmt Changed");
                            }
                        }
                        //	Different Date/CashBook
                        if (_cashLine != null
                            && (newC_CashBook_ID != _C_CashBook_ID
                                || !TimeUtil.IsSameDay(_cashLine.GetStatementDate(), newDateAcct)))
                        {
                            log.Config("Changed CashBook/Date: " + _C_CashBook_ID + "->" + newC_CashBook_ID);
                            MCashLine reverse = _cashLine.CreateReversal();
                            if (!reverse.Save())
                            {
                                ShowMessage.Error("", true, "PaymentError" + Msg.GetMsg(Envs.GetContext(), "CashNotCancelled", true).ToString());
                            }
                            _cashLine = null;
                        }

                        //	Create new
                        if (_cashLine == null)
                        {
                            log.Config("New CashBook");
                            int C_Currency_ID = 0;
                            if (invoice != null)
                            {
                                C_Currency_ID = invoice.GetC_Currency_ID();
                            }
                            if (C_Currency_ID == 0 && order != null)
                            {
                                C_Currency_ID = order.GetC_Currency_ID();
                            }
                            MCash cash = null;
                            if (newC_CashBook_ID != 0)
                            {
                                cash = MCash.Get(Envs.GetContext(), newC_CashBook_ID, newDateAcct, null);
                            }
                            else	//	Default
                            {
                                cash = MCash.Get(Envs.GetContext(), _AD_Org_ID, newDateAcct, C_Currency_ID, null);
                            }
                            if (cash == null || cash.Get_ID() == 0)
                            {
                                ShowMessage.Error("", true, "PaymentError" + Msg.GetMsg(Envs.GetContext(), "CashNotCreated", true).ToString());
                            }
                            else
                            {
                                MCashLine cl = new MCashLine(cash);
                                if (invoice != null)
                                {
                                    cl.SetInvoice(invoice);
                                }
                                if (order != null)
                                {
                                    cl.SetOrder(order, null);
                                    _needSave = true;
                                }
                                if (cl.Save())
                                {
                                    log.Config("CashCreated");
                                }
                                else
                                {
                                    ShowMessage.Error("", true, "PaymentError" + Msg.GetMsg(Envs.GetContext(), "CashNotCreated", true).ToString());
                                }
                            }
                        }
                    }	//	have invoice
                }
                /***********************
                 *  Payments
                 */
                if ("KS".IndexOf(newPaymentRule) != -1)
                {
                    //log.fine("Payment - " + newPaymentRule);
                    //  Set Amount
                    _mPayment.SetAmount(_C_Currency_ID, payAmount);
                    if (newPaymentRule.Equals(MOrder.PAYMENTRULE_CreditCard))
                    {
                        _mPayment.SetCreditCard(MPayment.TRXTYPE_Sales, newCCType,
                            txtKNumber.Text, "", txtKExp.Text);
                        _mPayment.SetPaymentProcessor();
                    }
                    else if (newPaymentRule.Equals(MOrder.PAYMENTRULE_Check))
                    {
                        _mPayment.SetBankCheck(newC_BankAccount_ID, _isSOTrx, txtSRouting.Text,
                            txtSNumber.Text, txtSCheck.Text);
                    }
                    _mPayment.SetC_BPartner_ID(_C_BPartner_ID);
                    _mPayment.SetC_Invoice_ID(C_Invoice_ID);
                    if (order != null)
                    {
                        _mPayment.SetC_Order_ID(C_Order_ID);
                        _needSave = true;
                    }
                    _mPayment.SetDateTrx(_DateAcct);
                    _mPayment.SetDateAcct(_DateAcct);
                    _mPayment.Save();

                    //  Save/Post
                    if (MPayment.DOCSTATUS_Drafted.Equals(_mPayment.GetDocStatus()))
                    {
                        bool ok = _mPayment.ProcessIt(DocActionVariables.ACTION_COMPLETE);
                        _mPayment.Save();
                        if (ok)
                        {
                            ShowMessage.Info(_mPayment.GetDocumentNo().ToString(), true, "PaymentCreated", "");
                        }
                        else
                        {
                            ShowMessage.Error("", true, "PaymentError" + Msg.GetMsg(Envs.GetContext(), "PaymentNotCreated", true).ToString());
                        }
                    }
                    else
                    {
                        log.Fine("NotDraft " + _mPayment);
                    }
                }


                /**********************
                 *	Save Values to mTab
                 */
                log.Config("Saving changes");

                //
                if (!newPaymentRule.Equals(_PaymentRule))
                {
                    _mTab.SetValue("PaymentRule", newPaymentRule);
                }
                //
                if (!newDateAcct.Equals(_DateAcct))
                {
                    _mTab.SetValue("DateAcct", newDateAcct);
                }
                //
                if (newC_PaymentTerm_ID != _C_PaymentTerm_ID)
                {
                    _mTab.SetValue("C_PaymentTerm_ID", newC_PaymentTerm_ID);
                }
                //	Set Payment
                if (_mPayment.GetC_Payment_ID() != _C_Payment_ID)
                {
                    if (_mPayment.GetC_Payment_ID() == 0)
                    {
                        _mTab.SetValue("C_Payment_ID", null);
                    }
                    else
                    {
                        _mTab.SetValue("C_Payment_ID", _mPayment.GetC_Payment_ID());
                    }
                }
                //	Set Cash
                if (newC_CashLine_ID != _C_CashLine_ID)
                {
                    if (newC_CashLine_ID == 0)
                    {
                        _mTab.SetValue("C_CashLine_ID", null);
                    }
                    else
                    {
                        _mTab.SetValue("C_CashLine_ID", newC_CashLine_ID);
                    }
                }
            }
            catch (Exception ex)
            {
                log.Severe(ex.ToString());
            }
            return true;
        }

        /// <summary>
        /// Check Mandatory
        /// </summary>
        /// <returns>true if all mandatory items are OK</returns>
        private bool CheckMandatory()
        {
            bool dataOK = true;
            try
            {
                //	log.config( "VPayment.checkMandatory");

                ValueNamePair vp = (ValueNamePair)cmbPayment.SelectedItem;
                if (vp.GetValue() == null)
                {
                    return false;
                }
                String PaymentRule = vp.GetValue();
                //  only Payment Rule
                if (_onlyRule)
                {
                    return true;
                }

                DateTime? DateAcct = _DateAcct;
                int C_PaymentTerm_ID = _C_PaymentTerm_ID;
                int C_CashBook_ID = _C_CashBook_ID;
                String CCType = _CCType;
                //
                int C_BankAccount_ID = 0;

                /***********************
                 *	Mandatory Data Check
                 */

                //	B (Cash)		(Currency)
                if (PaymentRule.Equals(MOrder.PAYMENTRULE_Cash))
                {
                    KeyNamePair kp = (KeyNamePair)cmbBCashBook.SelectedItem;
                    if (kp != null)
                    {
                        C_CashBook_ID = kp.GetKey();
                    }
                    DateAcct = (DateTime)bDateField.Value;
                }

                //	K (CreditCard)  Type, Number, Exp, Approval
                else if (PaymentRule.Equals(MOrder.PAYMENTRULE_CreditCard))
                {
                    vp = (ValueNamePair)cmbKType.SelectedItem;
                    if (vp != null)
                    {
                        CCType = vp.GetValue();
                    }
                    //
                    String error = MPaymentValidate.ValidateCreditCardNumber(txtKNumber.Text, CCType);
                    if (error.Length != 0)
                    {
                   
                        txtKNumber.Background = new SolidColorBrush(GlobalVariable.MANDATORY_TEXT_BACK_COLOR);
                        if (error.IndexOf("?") == -1)
                        {
                            ShowMessage.Error("", true, Msg.GetMsg(Envs.GetContext(), error, true).ToString());
                            dataOK = false;
                        }
                        else    //  warning
                        {
                            if (!ShowMessage.Ask("", true, error))
                            {
                                dataOK = false;
                            }
                        }
                    }
                    error = MPaymentValidate.ValidateCreditCardExp(txtKExp.Text);
                    if (error.Length != 0)
                    {
                        txtKExp.Background = new SolidColorBrush(GlobalVariable.MANDATORY_TEXT_BACK_COLOR);
                        ShowMessage.Error("", true, Msg.GetMsg(Envs.GetContext(), error, true).ToString());
                        dataOK = false;
                    }
                }

                //	T (Transfer)	BPartner_Bank
                else if (PaymentRule.Equals(X_C_Order.PAYMENTRULE_DirectDeposit)
                    || PaymentRule.Equals(X_C_Order.PAYMENTRULE_DirectDebit))
                {
                    KeyNamePair bpba = (KeyNamePair)cmbTAccount.SelectedItem;
                    if (bpba == null)
                    {
                        cmbTAccount.Background = new SolidColorBrush(GlobalVariable.MANDATORY_TEXT_BACK_COLOR);
                        ShowMessage.Error("", true, Msg.GetMsg(Envs.GetContext(), "PaymentBPBankNotFound", true).ToString());
                        dataOK = false;
                    }
                }	//	Direct

                //	P (PaymentTerm)	PaymentTerm
                else if (PaymentRule.Equals(X_C_Order.PAYMENTRULE_OnCredit))
                {
                    KeyNamePair kp = (KeyNamePair)cmbPTerm.SelectedItem;
                    if (kp != null)
                    {
                        C_PaymentTerm_ID = kp.GetKey();
                    }
                }

                //	S (Check)		(Currency) CheckNo, Routing
                else if (PaymentRule.Equals(MOrder.PAYMENTRULE_Check))
                {
                    //	cmbSCurrency.SelectedItem;
                    KeyNamePair kp = (KeyNamePair)cmbSBankAccount.SelectedItem;
                    if (kp != null)
                    {
                        C_BankAccount_ID = kp.GetKey();
                    }
                    String error = MPaymentValidate.ValidateRoutingNo(txtSRouting.Text);
                    if (error.Length != 0)
                    {
                        txtSRouting.Background = new SolidColorBrush(GlobalVariable.MANDATORY_TEXT_BACK_COLOR);
                        ShowMessage.Error("", true, Msg.GetMsg(Envs.GetContext(), error, true).ToString());
                        dataOK = false;
                    }
                    error = MPaymentValidate.ValidateAccountNo(txtSNumber.Text);
                    if (error.Length != 0)
                    {
                        txtSNumber.Background = new SolidColorBrush(GlobalVariable.MANDATORY_TEXT_BACK_COLOR);
                        ShowMessage.Error("", true, Msg.GetMsg(Envs.GetContext(), error, true).ToString());
                        dataOK = false;
                    }
                    error = MPaymentValidate.ValidateCheckNo(txtSCheck.Text);
                    if (error.Length != 0)
                    {
                        txtSCheck.Background = new SolidColorBrush(GlobalVariable.MANDATORY_TEXT_BACK_COLOR);
                        ShowMessage.Error("", true, Msg.GetMsg(Envs.GetContext(), error, true).ToString());
                        dataOK = false;
                    }
                }
                else
                {
                    log.Log(Level.SEVERE, "Unknown PaymentRule " + PaymentRule);
                    return false;
                }

                //  find Bank Account if not qualified yet
                if ("KTSD".IndexOf(PaymentRule) != -1 && C_BankAccount_ID == 0)
                {
                    String tender = MPayment.TENDERTYPE_CreditCard;
                    if (PaymentRule.Equals(MOrder.PAYMENTRULE_DirectDeposit))
                    {
                        tender = MPayment.TENDERTYPE_DirectDeposit;
                    }
                    else if (PaymentRule.Equals(MOrder.PAYMENTRULE_DirectDebit))
                    {
                        tender = MPayment.TENDERTYPE_DirectDebit;
                    }
                    else if (PaymentRule.Equals(MOrder.PAYMENTRULE_Check))
                    {
                        tender = MPayment.TENDERTYPE_Check;
                    }
                    //	Check must have a bank account
                    if (C_BankAccount_ID == 0 && "S".Equals(PaymentRule))
                    {
                        ShowMessage.Error("", true, Msg.GetMsg(Envs.GetContext(), "PaymentNoProcessor", true).ToString());
                        dataOK = false;
                    }
                }
            }
            catch (Exception ex)
            {
                log.Severe(ex.ToString());
            }
            log.Config("OK=" + dataOK);
            return dataOK;
        }

        /// <summary>
        /// Get Invoice ID for Order
        /// </summary>
        /// <param name="C_Order_ID">order</param>
        /// <returns>C_Invoice_ID or 0 if not found</returns>
        private static int GetInvoiceID(int C_Order_ID)
        {
            int retValue = 0;
            String sql = "SELECT C_Invoice_ID FROM C_Invoice WHERE C_Order_ID=" + C_Order_ID
                + "ORDER BY C_Invoice_ID DESC";     //  last invoice
            DataTable dt = null;
            IDataReader idr = null;
            try
            {

                idr = DB.ExecuteReader(sql, null, null);
                dt = new DataTable();
                dt.Load(idr);
                idr.Close();
                foreach (DataRow dr in dt.Rows)
                {
                    retValue = Util.GetValueOfInt(dr[0]);//.getInt(1);
                }

            }
            catch (Exception e)
            {
                if (idr != null)
                {
                    idr.Close();
                }
                log.Log(Level.SEVERE, sql, e);
            }
            finally
            {
                if (idr != null)
                {
                    idr.Close();
                }
                dt = null;
            }
            return retValue;
        }

        /// <summary>
        /// Process Online (sales only) - if approved - exit
        /// </summary>
        private void ProcessOnline()
        {
            try
            {
                log.Config("");
                if (!CheckMandatory())
                {
                    return;
                }

                bool approved = false;
                String info = "";
                //
                ValueNamePair vp = (ValueNamePair)cmbPayment.SelectedItem;
                String PaymentRule = vp.GetValue();

                //  --  CreditCard
                if (PaymentRule.Equals(X_C_Order.PAYMENTRULE_CreditCard))
                {
                    vp = (ValueNamePair)cmbKType.SelectedItem;
                    String CCType = vp.GetValue();

                    _mPayment.SetCreditCard(MPayment.TRXTYPE_Sales, CCType, txtKNumber.Text, "", txtKExp.Text);
                    _mPayment.SetAmount(_C_Currency_ID, _Amount);
                    _mPayment.SetPaymentProcessor();
                    _mPayment.SetC_BPartner_ID(_C_BPartner_ID);
                    //
                    int C_Invoice_ID = Envs.GetContext().GetContextAsInt(_WindowNo, "C_Invoice_ID");
                    if (C_Invoice_ID == 0 && _DocStatus.Equals("CO"))
                    {
                        int C_Order_ID = Envs.GetContext().GetContextAsInt(_WindowNo, "C_Order_ID");
                        C_Invoice_ID = GetInvoiceID(C_Order_ID);
                    }
                    _mPayment.SetC_Invoice_ID(C_Invoice_ID);
                    _mPayment.SetDateTrx(_DateAcct);
                    //  Set Amount
                    _mPayment.SetAmount(_C_Currency_ID, _Amount);
                    approved = _mPayment.ProcessOnline();
                    info = _mPayment.GetR_RespMsg() + " (" + _mPayment.GetR_AuthCode()
                        + ") ID=" + _mPayment.GetR_PnRef();
                    bool saved = _mPayment.Save();

                    if (approved)
                    {
                        bool ok = _mPayment.ProcessIt(DocActionVariables.ACTION_COMPLETE);
                        _mPayment.Save();
                        if (ok)
                        {
                            //ADialog.info(_WindowNo, this, "PaymentProcessed", info + "\n" + _mPayment.GetDocumentNo());
                            ShowMessage.Info("", true, "PaymentProcessed", info + "\n" + _mPayment.GetDocumentNo());
                        }
                        else
                        {
                            //ADialog.error(_WindowNo, this, "PaymentError", "PaymentNotCreated");
                            ShowMessage.Error("", true, "PaymentError " + Msg.GetMsg(Envs.GetContext(), "PaymentNotCreated", true).ToString());
                            //ShowMessage.Error("", true, "PaymentError--PaymentNotCreated");
                        }
                        SaveChanges();
                        //Dispose();
                        this.DialogResult = true;
                    }
                    else
                    {
                        ShowMessage.Error("", true, Msg.GetMsg(Envs.GetContext(), "PaymentNotProcessed", true).ToString());
                    }
                }
                else
                {
                    ShowMessage.Error("", true, Msg.GetMsg(Envs.GetContext(), "PaymentNoProcessor", true).ToString());
                }
            }
            catch (Exception ex)
            {
                log.Severe(ex.ToString());
            }
        }

        /// <summary>
        /// Need Save record (payment with waiting order)
        /// </summary>
        /// <returns>true if payment with waiting order</returns>
        public bool NeedSave()
        {
            return _needSave;
        }

        #region Event Region

        /// <summary>
        /// Ok button click event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OKButton_Click(object sender, RoutedEventArgs e)
        {
            if (CheckMandatory())
            {
                SaveChanges(); // cannot recover
                // Dispose();
                this.DialogResult = true;
            }
        }

        /// <summary>
        /// Cancel button click event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void btnKOnline_Click(object sender, RoutedEventArgs e)
        {
            ProcessOnline();
        }

        /// <summary>
        /// onlineButton click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void btnSOnline_Click(object sender, RoutedEventArgs e)
        {
            // ProcessOnline();
        }

        /// <summary>
        /// Chash book combo change event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void cmbBCashBook_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }

        /// <summary>
        /// Sbank Account combo
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void cmbSBankAccount_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }

        /// <summary>
        /// Pterm combo
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void cmbPTerm_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }

        /// <summary>
        /// Bcurrency change event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void cmbBCurrency_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            KeyNamePair pp = (KeyNamePair)cmbBCurrency.SelectedItem;
            Decimal amt = MConversionRate.Convert(Envs.GetContext(),
                _Amount, _C_Currency_ID, pp.GetKey(), _AD_Client_ID, _AD_Org_ID);
            //lblBAmountField.Text=_Format.format(amt);
        }

        /// <summary>
        /// Currency change event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void cmbSCurrency_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            KeyNamePair pp = (KeyNamePair)cmbSCurrency.SelectedItem;
            Decimal amt = MConversionRate.Convert(Envs.GetContext(),
                _Amount, _C_Currency_ID, pp.GetKey(), _AD_Client_ID, _AD_Org_ID);
            //lblSAmountField.Text = _Format.format(amt);
        }

        /// <summary>
        /// Transaction Account event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void cmbTAccount_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }

        /// <summary>
        /// Credit combo change event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void cmbKType_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }

        /// <summary>
        /// Payment combo change event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void cmbPayment_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //	get selection
            ValueNamePair pp = (ValueNamePair)cmbPayment.SelectedItem;
            if (pp != null)
            {
                String s = pp.GetValue().ToLower();
                //if (X_C_Order.PAYMENTRULE_DirectDebit.equalsIgnoreCase(s))
                if (X_C_Order.PAYMENTRULE_DirectDebit == s.ToLower() || X_C_Order.PAYMENTRULE_DirectDebit == s.ToUpper())
                {
                    s = X_C_Order.PAYMENTRULE_DirectDeposit.ToLower();
                }
                s += "Panel";
                //centerLayout.Show(centerPanel, s);	//	switch to panel
                // centerPanel.Show();

                if (pp.Key.Equals("K"))
                {
                    this.kPanel.Visibility = System.Windows.Visibility.Visible;
                    this.pPanel.Visibility = System.Windows.Visibility.Collapsed;
                    this.bPanel.Visibility = System.Windows.Visibility.Collapsed;
                    this.tPanel.Visibility = System.Windows.Visibility.Collapsed;
                    this.sPanel.Visibility = System.Windows.Visibility.Collapsed;
                }
                else if (pp.Key.Equals("B"))
                {
                    this.kPanel.Visibility = System.Windows.Visibility.Collapsed;
                    this.pPanel.Visibility = System.Windows.Visibility.Collapsed;
                    this.bPanel.Visibility = System.Windows.Visibility.Visible;
                    this.tPanel.Visibility = System.Windows.Visibility.Collapsed;
                    this.sPanel.Visibility = System.Windows.Visibility.Collapsed;
                }
                else if (pp.Key.Equals("D"))
                {
                    this.kPanel.Visibility = System.Windows.Visibility.Collapsed;
                    this.pPanel.Visibility = System.Windows.Visibility.Collapsed;
                    this.bPanel.Visibility = System.Windows.Visibility.Collapsed;
                    this.tPanel.Visibility = System.Windows.Visibility.Visible;
                    this.sPanel.Visibility = System.Windows.Visibility.Collapsed;
                }
                else if (pp.Key.Equals("P"))
                {
                    this.kPanel.Visibility = System.Windows.Visibility.Collapsed;
                    this.pPanel.Visibility = System.Windows.Visibility.Visible;
                    this.bPanel.Visibility = System.Windows.Visibility.Collapsed;
                    this.tPanel.Visibility = System.Windows.Visibility.Collapsed;
                    this.sPanel.Visibility = System.Windows.Visibility.Collapsed;
                }
                else if (pp.Key.Equals("S"))
                {
                    this.kPanel.Visibility = System.Windows.Visibility.Collapsed;
                    this.pPanel.Visibility = System.Windows.Visibility.Collapsed;
                    this.bPanel.Visibility = System.Windows.Visibility.Collapsed;
                    this.tPanel.Visibility = System.Windows.Visibility.Collapsed;
                    this.sPanel.Visibility = System.Windows.Visibility.Visible;
                }
                else if (pp.Key.Equals("T"))
                {
                    this.kPanel.Visibility = System.Windows.Visibility.Collapsed;
                    this.pPanel.Visibility = System.Windows.Visibility.Collapsed;
                    this.bPanel.Visibility = System.Windows.Visibility.Collapsed;
                    this.tPanel.Visibility = System.Windows.Visibility.Collapsed;
                    this.sPanel.Visibility = System.Windows.Visibility.Collapsed;
                }

            }
        }

        #endregion

        private void busyWindow_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            e.Handled = true;
        }
    }
}

